/**
 基本信息
*/
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import config from './config';
import { connect } from 'dva';
import { calculateFee } from '../../../../utils/commonFunc';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import _ from 'lodash';
import tradingCodeDate from '../../../../utils/enumeratedValues/blackOrder';
class BaseInfoC extends PureComponent {
  static defaultProps = {
    onRef: () => {}, //本组件
  };
  constructor(props) {
    super(props);
    this.state = {
      isRequired: true, //是否必填
      tradingCodeList: [], //交易标的
      isCanOrder: true, //是否可以下达 默认可以下达
      feeData: {
        //费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        exchangecode: '101',
        sectype: 'hg',
        sectypeii: 'zyshg',
        orderside: '1',
        price: undefined,
      },
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.info) != JSON.stringify(this.props.info)) {
      //审批信息那边的数据 延时传递
      this.handleSelectValue(nextProps.info.orderSide, '2');
    }
  }

  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 4) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ 'trade7.fee': undefined });
        if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
          let fee = calculateFee(this.state.feeData);
          fee.then((r) => {
            setFieldsValue({ 'trade7.fee': r });
          });
        });
      }
    }, 100);
  };

  //组合id变更
  groupOnChange = (e) => {
    this.props.portfolioOnChange(e ? e.key : undefined); //抛出组合id
    if (e) this.handleSelectValue(e.key, '3');
    if (e && this.props.type == 1) {
      //新增指令时 需要判断该组合是否进行了指令配置
      this.props.dispatch({
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: e.key,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else if (!e && this.props.type == 1) {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  //根据委托数量计算--委托金额
  onBlurOrderuseQty = (type) => {
    const { getFieldsValue, setFieldsValue } = this.formGroupThis.props.form;
    let item = getFieldsValue();
    if ('Qty' === type && item.trade7.orderuseQty) {
      //数量变更
      let orderuseQty = parseInt(item.trade7.orderuseQty) * 100;
      setFieldsValue({
        'trade7.orderAmount': orderuseQty,
      });
      this.changeFee('price', orderuseQty);
    } else if ('Amount' === type && item.trade7.orderAmount) {
      //金额变更
      let orderAmount = parseInt(item.trade7.orderAmount) / 100;
      setFieldsValue({
        'trade7.orderuseQty': orderAmount,
      });
      this.changeFee('price', item.trade7.orderAmount);
    }
  };

  //查询交易标的
  handleSelectValue = (value, type) => {
    // type 1交易所 2 委托方向 3组合id
    const { setFieldsValue, getFieldValue } = this.formGroupThis.props.form;
    setTimeout(() => {
      if (this.props.type != 3) setFieldsValue({ 'trade7.tradingcode': undefined }); //详情时不进行重置
      let portfolioId = getFieldValue('trade7.portfolioId');
      let orderSide = getFieldValue('trade7.orderSide');
      let tradingmarket = getFieldValue('trade7.tradingmarket');

      //交易所改变
      if (type === '1') {
        this.getTradingCodeList(orderSide, tradingmarket, portfolioId);
      }
      // 委托方向改变
      if (type == '2') {
        if (this.props.type != 3) {
          setFieldsValue({
            'trade7.orderPrice': undefined,
            'trade7.orderAmount': undefined,
            'trade7.orderuseQty': undefined,
          });
          this.changeFee('price', undefined);
        }
        if (orderSide === '1' || orderSide === '2') {
          this.setState({
            isRequired: true,
          });
        } else {
          this.setState({
            isRequired: false,
          });
        }
        this.getTradingCodeList(orderSide, tradingmarket, portfolioId);
      }

      // 组合改变
      if (type == '3') {
        setFieldsValue({
          'trade7.orderSide': '1',
        });
        this.getTradingCodeList('1', tradingmarket, portfolioId);
      }
    }, 0);
  };

  getTradingCodeList = (orderSide, tradingMarket, portfolioId) => {
    const {
      exchangePledgeM: { holdData = [] },
    } = this.props;
    // 方向为融资、融券回购时
    if (orderSide == '1' || orderSide == '2' || !orderSide) {
      if (!orderSide || !tradingMarket) {
        this.setState({
          tradingCodeList: [],
        });
        return;
      }
      this.setState({
        tradingCodeList: tradingCodeDate[tradingMarket],
      });
    } else {
      // 方向为提交、转回质押时
      const arr = [];
      const orderType = orderSide == '3' ? 'transformAmount' : 'pledgeAmount';
      const tradingType = tradingMarket == '101' ? '1' : '2';
      // 组合为空时清空证券代码
      if (!portfolioId) {
        this.setState({
          tradingCodeList: [],
        });
        return;
      }

      holdData.map((item) => {
        if (item.exchangeCode == tradingType && item[orderType] > 0) {
          arr.push({
            value: item.tradingcode,
            title: `${item.tradingcode}-${item.secuabbr}`,
          });
        }
      });

      this.setState({
        tradingCodeList: arr,
      });
    }
  };
  render() {
    const { isRequired, tradingCodeList } = this.state;
    const {
      type,
      listId,
      info = {},
      user: { currentUser },
    } = this.props;
    return (
      <FormGroup
        dataSource={[
          type == '10'
            ? {
                dataIndex: 'listId',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                rules: [{ required: true, message: '请选择系列产品!' }],
                disabled: true,
                initialValue: listId,
                onChange: (e) => {
                  this.handleSelectValue(e?.value, '3');
                  this.props.seriesProductsOnChange(e?.value); // 向外抛处系列产品id
                },
                span: 12,
                controlLabelSpan: 8,
              }
            : {
                title: ['产品', '组合'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                authority: 'write',
                multipleGroup: false,
                dataIndex: ['trade7.productId', 'trade7.portfolioId'],
                rules: [[{ required: true, message: '请选择产品' }], [{ required: true, message: '请选择组合' }]],
                groupOnChange: (e) => {
                  this.groupOnChange(e);
                  this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
                  this.changeFee('portfolioid', e ? e.key : undefined);
                },
                productOnChange: (e) => {
                  this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
                  this.changeFee('productId', e ? e.key : undefined);
                  this.setState({
                    tradingCodeList: [],
                  });
                },
                allowClear: false,
                disabled: type == 3 ? true : false,
                initialValue: [info.portfolioInfoId ? info.portfolioInfoId : undefined, info.productId ? info.productId : undefined],
                exist: 1,
                span: 12,
                controlLabelSpan: 8,
                tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
              },
          {
            title: '交易市场',
            dataIndex: 'trade7.tradingmarket',
            type: DATA_ENTRY.TRADINGMARKET,
            initialValue: info.trade7 && info.trade7.tradingmarket ? info.trade7.tradingmarket : '101',
            rules: [{ required: true, message: '请选择交易所' }],
            onChange: (e) => {
              this.handleSelectValue(e, '1');
              this.changeFee('exchangecode', e ? e.value : '101');
            },
            disabled: type == 3 ? true : false,
            span: 6,
            controlLabelSpan: 8,
            onRef: (ref) => (this.formGroupThis = ref),
          },
          type == 10
            ? {
                title: '交易方向', //交易录入时 只要融券融资
                dataIndex: 'trade7.orderSide',
                type: DATA_ENTRY.SELECT,
                dataSource: config.tradeDir,
                rules: [{ required: true, message: '请选择交易方向!' }],
                multiple: false,
                disabled: false,
                initialValue: '1',
                onChange: (e) => {
                  //只是入参和展示上的区别 其余按照原有的direct的数值传参 1和2传1 3和4传2
                  if (!e) return;
                  this.handleSelectValue({ value: e }, '2');
                },
                span: 6,
                controlLabelSpan: 8,
              }
            : {
                title: '交易方向',
                dataIndex: 'trade7.orderSide',
                type: DATA_ENTRY.TRADINGDIRECT,
                businessType: '7',
                appType: type == 11 ? '4' : type == 1 ? '0' : '1',
                initialValue: info.trade7 && info.trade7.orderSide ? info.trade7.orderSide : '1',
                rules: [{ required: true, message: '请选择交易方向!' }],
                onChange: (e) => {
                  this.handleSelectValue(e, '2');
                  this.changeFee('orderside', e?.value);
                },
                disabled: type == 3 ? true : false,
                span: 6,
                controlLabelSpan: 8,
              },
          {
            title: '证券代码',
            dataIndex: 'trade7.tradingcode',
            type: DATA_ENTRY.SELECT,
            allowClear: true,
            placeholder: '请选择',
            optionTitle: true,
            rules: [{ required: true, message: '请选择交易标的!' }],
            dataSource: tradingCodeList,
            disabled: type == 3 ? true : false,
            filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
            initialValue: info.trade7 && info.trade7.tradingcode ? info.trade7.tradingcode : undefined,
            onChange: (e) => {
              this.changeFee('tradingCode', e);
            },
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: type == 2 ? '成交数量' : '委托数量',
            dataIndex: 'trade7.orderuseQty',
            type: DATA_ENTRY.INPUTNUMBER,
            rules: [
              { required: true, message: '请输入委托数量!' },
              { pattern: /^[+-]?(\d){1,}0$/, message: '请输入10的倍数' },
            ],
            precision: 0,
            unit: '张',
            // max: type == 10 ? undefined : 1000000, //交易录入时对数量不做限制
            splitStyle: true,
            onBlur: () => this.onBlurOrderuseQty('Qty'),
            disabled: type == 3 ? true : false,
            initialValue: info.trade7 && info.trade7.orderuseQty ? info.trade7.orderuseQty : undefined,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: type == 2 ? '成交金额' : '委托金额',
            dataIndex: 'trade7.orderAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            rules: [
              { required: isRequired, message: '请输入委托金额!' },
              { pattern: /^[+-]?(\d){1,}000$/, message: '请输入1000的倍数' },
            ],
            precision: 0,
            max: type == 10 ? undefined : 999999999999, //交易录入时 金额不做限制
            onBlur: () => this.onBlurOrderuseQty('Amount'),
            splitStyle: true,
            disabled: type == 3 ? true : !isRequired,
            initialValue: info.trade7 && info.trade7.orderAmount ? info.trade7.orderAmount : undefined,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '回购利率',
            dataIndex: 'trade7.orderPrice',
            type: DATA_ENTRY.INPUTNUMBER,
            rules: [
              { required: isRequired, message: '请输入回购利率!' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '回购利率必须大于0' },
            ],
            unit: '%',
            precision: 2,
            splitStyle: true,
            disabled: type == 3 ? true : !isRequired,
            initialValue: info.trade7 && info.trade7.orderPrice && info.trade7.orderSide < 3 ? info.trade7.orderPrice : undefined,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            title: '投资类型',
            dataIndex: 'trade7.investmentType',
            type: DATA_ENTRY.SELECT,
            initialValue: info.trade7 ? info.trade7.investmentType : 'AC',
            disabled: type == 3 ? true : false,
            dataSource: investmentTypeData,
            allowClear: true,
            rules: [{ required: false, message: '请选择' }],
            span: 6,
            controlLabelSpan: 8,
            hide: type == 10,
          },
          {
            title: '费用',
            dataIndex: 'trade7.fee',
            type: DATA_ENTRY.INPUTNUMBER,
            disabled: type == '3' ? true : false,
            unit: '元',
            span: 6,
            controlLabelSpan: 8,
            hide: type != 10,
          },
          {
            title: '下达人', // 显示名称
            dataIndex: 'trade7.creator', // Form识别的Item ID
            type: DATA_ENTRY.INPUT,
            initialValue: info.userName ? info.userName : currentUser.name,
            disabled: true,
            span: 6,
            controlLabelSpan: 8,
          },
          {
            dataIndex: 'trade7.describe',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: type == 3 ? true : false,
            initialValue: info.trade7 && info.trade7.describe ? info.trade7.describe : undefined,
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
            controlLabelSpan: 2,
          },
        ]}
        autoLayout={false}
        rowNumber={4}
      />
    );
  }
}
export default connect(({ exchangePledgeM, isAccountConfiguredM, userM: user, loading }) => ({
  exchangePledgeM,
  isAccountConfiguredM,
  user,
  loading,
}))(Form.create()(BaseInfoC));
